/*
 * GeoVISTA Center (Penn State, Dept. of Geography)
 * Copyright (c), 2003-2011,  Jin Chen and Alan M. MacEachren, GeoVISTA Center, Penn State University
 * Licensed under Simplified BSD License
 *
 *
 * @Original Author: jin Chen
 * @date: Apr 25, 2006$
 * @version: 1.0
 */
package edu.psu.geovista.common.xml.dom4j;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Iterator;

public class XMLParserDom4j {

   public static final boolean DEBUG=false;



    public static Document loadDocument(File file) throws Exception {
        //System.out.println(XMLParserDom4j.class.getName() +" create SAXReader-->");
        SAXReader reader = new SAXReader();
       //System.out.println(XMLParserDom4j.class.getName() +" <--create SAXReader");
        Document document = null;
        try {
            System.out.println(XMLParserDom4j.class.getName() +" ready to read file "+file.getAbsolutePath() );
            document = reader.read(file);
            System.out.println(XMLParserDom4j.class.getName() +" complete read file "+file.getAbsolutePath() );

        } catch (DocumentException e) {
            throw e;
           // e.printStackTrace();  //To change body of catch statement use Options | File Templates.
        } catch (MalformedURLException e) {
            throw e;
           // e.printStackTrace();  //To change body of catch statement use Options | File Templates.
        }
        return document;

    }
    public static Document loadDocument(InputStream input) throws Exception {
        SAXReader reader = new SAXReader();
        Document document = null;
      /*  URL classLocation = JSwingUtils.getClassLocation(SAXReader.class);
        System.out.println("classLocation"+classLocation);*/
        try {
            document = reader.read(input);
        } catch (DocumentException e) {
            throw e;
           // e.printStackTrace();  //To change body of catch statement use Options | File Templates.
        }
        return document;

    }
    public static void saveDocument(Document document, File file) throws IOException {

            // lets write to a file
            OutputFormat format = OutputFormat.createPrettyPrint();
            XMLWriter writer = new XMLWriter(
                new FileWriter(file),format// "output.xml" )
            );
            writer.write( document );
            writer.close();

        if (DEBUG) {

            System.out.println("Pretty print the document to System.out ->");
            // Pretty print the document to System.out
            format = OutputFormat.createPrettyPrint();
            writer = new XMLWriter( System.out, format );
            writer.write( document );

            System.out.println("Compact format to System.out ->");
            // Compact format to System.out
           /* format = OutputFormat.createCompactFormat();
            writer = new XMLWriter( System.out, format );
            writer.write( document );*/
        }
    }
     /**
     * E.g.:
     *      <root>
                  <author id="James" location="UK">James Strachan </author>
                  <author id="Bob" location="US">Bob McWhirter</author>
             </root>
     *      getChildElement(doc.getRootElement() ,"author", "James") will return the element <author id="James" location="UK">James Strachan </author>;
     * @param parent
     * @param tagName
     * @param attrName
     * @param attrValue
     * @return        direct child element with given tagName and its attribute <attrName>= given attrValue
     *
     */
    public static Element getChildElement(Element parent, String tagName,String attrName,String attrValue) {
         //String p=parent.asXML() ;

        Iterator childIter =parent.elementIterator();

        while(childIter.hasNext()){
            Element child= (Element)childIter.next();
            if(child.getQualifiedName().equals(tagName)&& child.attributeValue(attrName)!=null&&child.attributeValue(attrName).equals(attrValue) )
                return child;

        }
        return null;
    }
    /**
     * * E.g.:
     *      <root>
                  <author id="James" location="UK">James Strachan </author>
                  <author id="Bob" location="US">Bob McWhirter</author>
                  <time .../>
                  <book.../>
             </root>
     *       getChildElements("root","author") return <author> elements
     * @param parent
     * @param tagName
     * @return         direct child elements of parent with given tagName
     */
    public static ArrayList getChildElements(Element parent, String tagName) {
       Iterator childIter =parent.elementIterator();
        ArrayList elements=new ArrayList();
        while(childIter.hasNext()){
            Element child= (Element)childIter.next();
            if(child.getQualifiedName().equals(tagName))
                elements.add(child);
        }
        return elements;
    }

   /*******************************************************************************************************
    *                testing
    *******************************************************************************************************/
    /**
     * testing  writting
     * @return
     */
    private static Document createDocument() {
            Document document = DocumentHelper.createDocument();
            Element root = document.addElement( "root" );

            Element author1 = root.addElement( "author" )
                .addAttribute( "id", "James" )
                .addAttribute( "location", "UK" )
                .addText( "James Strachan" );

            Element author2 = root.addElement( "author" )
                .addAttribute( "id", "Bob" )
                .addAttribute( "location", "US" )
                .addText( "Bob McWhirter" );


            for (int i=0;i<3;i++){

                String name = "name "+i;
                String value="path "+i;
                Element path=author1.addElement("Path")
                            .addAttribute("Name",name)
                            .addAttribute("FullPath",value);
            }

            return document;

    }

    public static void main(String[] args) {
        Document doc=createDocument();
        XMLParserDom4j parser=new XMLParserDom4j();
        try {
            parser.saveDocument(doc, new File("output.xml"));
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use Options | File Templates.
        }
        Element element=getChildElement(doc.getRootElement(), "author","id","James");

        System.out.println(" return element:"+element.asXML());



    }
}
